import { Space, Avatar, Typography, Button, Modal, Input } from "antd";
import { CommentItem } from "./shareType.ts"; // 导入接口定义
import CommentReply from "./CommentReply.tsx";
import React, { useState } from "react";
import { userAddReply, userDeleteComment } from "@/apis/articlesApi.ts";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { ArticleDetail } from "@/apis/shared.ts";
import { formatDate } from "@/utils/tool.ts";

const { Paragraph } = Typography;

/**
 * 渲染评论
 * @param comment
 * @param level
 */
interface CommentItemProps {
  comment: CommentItem;
  level: number;
  setArticle: (article: ArticleDetail) => void;
  article: ArticleDetail;
}
const CommentRenderer: React.FC<CommentItemProps> = ({
  comment,
  level,
  article,
  setArticle,
}) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [commentValue, setCommentValue] = useState("");

  // 显示弹窗
  const showModal = () => {
    setIsModalOpen(true);
  };

  // 点击了确定按钮
  const handleOk = async () => {
    console.log("commentValue", commentValue);
    // 使用api向后端发送请求，添加文章评论的回复
    const res = await userAddReply(
      article._id,
      comment._id,
      commentValue,
      new Date().toISOString()
    );

    // 用户添加评论的回复
    if (res.code === 200) {
      // setArticle(); // 更新文章详情
      const commentItemIndex = article.commentList.findIndex(
        (item) => item._id === comment._id
      );

      //
      article.commentList[commentItemIndex] = res.data!;

      setArticle({ ...article, commentList: [...article.commentList] });
    }

    // 重置评论框
    setCommentValue("");

    // 关闭弹窗
    setIsModalOpen(false);
  };

  // 点击了取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 判断是否是这条评论的作者
  const flag = useSelector((state: RootState) => state.UserInfoStore.email);

  const [isUserComment] = useState(flag === comment.authorEmail);

  // 删除评论的逻辑
  const handleDeleteComment = async () => {
    // 调用api删除评论
    const res = await userDeleteComment(article._id, comment._id);

    // 用户删除评论
    if (res.code === 200) {
      // 更新文章详情
      setArticle({
        ...article,
        commentList: article.commentList.filter(
          (item) => item._id !== comment._id
        ),
      });
    }
  };

  return (
    <Space direction="vertical" style={{ paddingLeft: level * 20 }}>
      <Space>
        <Avatar
          src={comment.authorAvatar}
          shape="square"
          size={32 + level * 2}
        />
        <Typography.Text strong>{comment.authorNickName}</Typography.Text>
        <Typography.Text>{formatDate(comment.createTime)}</Typography.Text>
        <Typography.Text>
          <Button type="link" onClick={showModal}>
            回复
          </Button>{" "}
          {isUserComment && (
            <Button type="link" onClick={handleDeleteComment}>
              删除
            </Button>
          )}
          <Modal
            title="回复评论"
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Input.TextArea
              autoSize={{ minRows: 2, maxRows: 5 }}
              value={commentValue}
              onChange={(e) => setCommentValue(e.target.value)}
            />
          </Modal>
        </Typography.Text>
      </Space>
      <Paragraph>{comment.content}</Paragraph>
      {comment.replyList?.map((reply) => (
        <div key={reply._id}>
          <CommentReply
            article={article}
            reply={reply}
            commentId={comment._id}
            setArticle={setArticle}
            level={Math.min(level + 1, 1)}
          />
        </div>
      ))}
    </Space>
  );
};

export default CommentRenderer;
